package com.lh.nk;

/**
 * @author: linghao
 * @since: 2023/1/28
 *
 * 描述
 * 给定一个单链表的头结点pHead(该头节点是有值的，比如在下图，它的val是1)，长度为n，反转该链表后，返回新链表的表头。
 *
 * 如当输入链表{1,2,3}时，
 * 经反转后，原链表变为{3,2,1}，所以对应的输出为{3,2,1}。
 */
public class 反转链表NC78 {

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;

        for(ListNode cur = node1;cur != null;cur = cur.next){
            System.out.print(cur.val);
        }
        ListNode listNode = ReverseList(node1);
        for(ListNode cur = listNode;cur != null;cur = cur.next){
            System.out.print(cur.val);
        }
    }

    public static ListNode ReverseList(ListNode head) {
        ListNode newNode = null;
        while (head != null){
            ListNode temp = head.next;
            //这一步反转当前节点的的next指针
            head.next = newNode;
            newNode = head;
            head = temp;
        }
        return newNode;
    }


    public static  class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}


